import { zValidator } from "@hono/zod-validator";
import { Hono } from "hono";
import {
  getReportById,
  getReportNames,
  getReports,
  QueryReportsSchema,
  syncReport,
} from "../queries/reports";
import type { TaskLocator } from "../types/allure";

const app = new Hono()
  .get("/", zValidator("query", QueryReportsSchema), async (c) => {
    const data = await getReports(c.req.valid("query"));
    return c.json({ ok: true, data }, 200);
  })
  .get("/sync", async (c) => {
    const config: TaskLocator = {
      url: "https://chaocwu.github.io",
      name: "pytest-template",
      number: 12,
    };
    try {
      const report = await syncReport(config);
      return c.json({ ok: true, data: report }, 201);
    } catch (error) {
      return c.json(
        {
          ok: false,
          error: error instanceof Error ? error.message : "Unknown error",
        },
        400,
      );
    }
  })
  .get("/names", async (c) => {
    const data = await getReportNames();
    return c.json({ ok: true, data });
  })
  .get("/:id", async (c) => {
    const id = c.req.param("id");
    const data = await getReportById(id);
    return c.json({ ok: data !== undefined, data: data ?? null });
  });

export default app;
